<template>
  <div class="scenic-guide-container">
    <!-- 页面头部 -->
    <div class="scenic-guide-header">
      <div class="header-actions">
        <el-button type="primary" :icon="Back" @click="goBack">返回</el-button>
      </div>
      <h1>保护区浏览</h1>
      <p>浏览青岛自然保护区地理要素信息，查看保护区连线导览图</p>
    </div>

    <!-- 主要内容区域 -->
    <el-row :gutter="20">
      <!-- 左侧地图区域 -->
      <el-col :span="16">
        <el-card class="map-card">
          <template #header>
            <div class="card-header">
              <span>{{ getCurrentAreaName() }}保护区导览图</span>
            </div>
          </template>
          <div id="guideMapView" class="map-container"></div>
        </el-card>
      </el-col>

      <!-- 右侧功能区域 -->
      <el-col :span="8">
        <!-- 景区选择 -->
        <el-card class="area-select-card">
          <template #header>
            <div class="card-header">
              <span>保护区选择</span>
            </div>
          </template>

          <div class="area-tabs">
            <el-tabs v-model="activeArea" @tab-click="handleAreaChange">
              <el-tab-pane label="胶南灵山岛保护区" name="erdihu"></el-tab-pane>
              <el-tab-pane label="大公岛保护区" name="yunmen"></el-tab-pane>
              <el-tab-pane label="大泽山保护区" name="bailang"></el-tab-pane>
              <el-tab-pane label="崂山保护区" name="xiashan"></el-tab-pane>
              <el-tab-pane label="胶州艾山保护区" name="binhai"></el-tab-pane>
              <el-tab-pane label="马山保护区" name="mihe"></el-tab-pane>
            </el-tabs>
          </div>
        </el-card>

        <!-- 数据类型切换 -->
        <el-card class="data-type-card">
          <template #header>
            <div class="card-header">
              <span>数据类型</span>
            </div>
          </template>
          <el-radio-group v-model="dataType" @change="handleDataTypeChange">
            <el-radio-button label="protectArea">保护区</el-radio-button>
            <el-radio-button label="scenicPoint">景点</el-radio-button>
          </el-radio-group>
        </el-card>

        <!-- 保护区列表 -->
        <el-card class="feature-list-card" v-show="dataType === 'protectArea'">
          <template #header>
            <div class="card-header">
              <span>保护区列表</span>
              <el-input
                v-model="searchQuery"
                placeholder="搜索保护区"
                class="search-input"
                :prefix-icon="Search"
              />
            </div>
          </template>

          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="filteredTableData"
            style="width: 100%"
            @row-click="handleRowClick"
            highlight-current-row
            height="300"
          >
            <el-table-column prop="attributes.Name" label="保护区名称" />
            <el-table-column prop="attributes.AreaType" label="类型">
              <template #default="scope">
                <el-tag :type="getTypeTagType(scope.row.attributes.AreaType)">
                  {{ scope.row.attributes.AreaType || '未分类' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="viewFeatureDetailsFromButton(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 景点列表 -->
        <el-card class="feature-list-card" v-show="dataType === 'scenicPoint'">
          <template #header>
            <div class="card-header">
              <span>景点列表</span>
              <el-input
                v-model="scenicSearchQuery"
                placeholder="搜索景点名称"
                class="search-input"
                :prefix-icon="Search"
              />
            </div>
          </template>

          <el-table
            ref="scenicTableRef"
            v-loading="scenicLoading"
            :data="filteredScenicTableData"
            style="width: 100%"
            @row-click="handleScenicRowClick"
            highlight-current-row
            height="300"
          >
            <el-table-column prop="attributes.ScenicName" label="景点名称" />
            <el-table-column prop="attributes.ScenicType" label="类型">
              <template #default="scope">
                <el-tag :type="getScenicTypeTagType(scope.row.attributes.ScenicType)">
                  {{ scope.row.attributes.ScenicType || '未分类' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="attributes.Status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.attributes.Status)">
                  {{ scope.row.attributes.Status || '未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click.stop="viewScenicDetailsFromButton(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 保护区详情抽屉 -->
    <el-drawer
      v-model="showDetailsDrawer"
      title="保护区详情"
      direction="rtl"
      size="30%"
      v-if="dataType === 'protectArea'"
    >
      <div v-if="currentFeature" class="feature-details">
        <h2>{{ currentFeature.attributes.Name }}</h2>
        <el-divider />
        <p>
          <strong>类型：</strong>
          <el-tag :type="getTypeTagType(currentFeature.attributes.AreaType)">
            {{ currentFeature.attributes.AreaType || '未分类' }}
          </el-tag>
        </p>
        <p><strong>描述：</strong>{{ currentFeature.attributes.Description || '暂无描述' }}</p>
        <p><strong>门票：</strong>{{ currentFeature.attributes.Price || '免费' }}</p>
        <p><strong>开放时间：</strong>{{ currentFeature.attributes.OpeningHours || '全天开放' }}</p>
        <p><strong>地址：</strong>{{ currentFeature.attributes.Address || '详情咨询保护区' }}</p>
        <div class="details-actions">
          <el-button type="primary" @click="addToFavorites(currentFeature)">
            <el-icon><Star /></el-icon> 收藏
          </el-button>
        </div>
      </div>
      <div v-else class="no-feature-selected">
        <p>请选择一个保护区查看详情</p>
      </div>
    </el-drawer>

    <!-- 景点详情抽屉 -->
    <el-drawer
      v-model="showScenicDetailsDrawer"
      title="景点详情"
      direction="rtl"
      size="30%"
      v-if="dataType === 'scenicPoint'"
    >
      <div v-if="currentScenicFeature" class="feature-details">
        <h2>{{ currentScenicFeature.attributes.ScenicName }}</h2>
        <el-divider />

        <!-- 景点图片 -->
        <div v-if="currentScenicFeature.attributes.PhotoBase64" class="scenic-photo">
          <el-image
            style="width: 100%; max-height: 200px; margin-bottom: 15px"
            :src="currentScenicFeature.attributes.PhotoBase64"
            fit="cover"
          ></el-image>
        </div>

        <p>
          <strong>类型：</strong>
          <el-tag :type="getScenicTypeTagType(currentScenicFeature.attributes.ScenicType)">
            {{ currentScenicFeature.attributes.ScenicType || '未分类' }}
          </el-tag>
        </p>
        <p>
          <strong>状态：</strong>
          <el-tag :type="getStatusTagType(currentScenicFeature.attributes.Status)">
            {{ currentScenicFeature.attributes.Status || '未知' }}
          </el-tag>
        </p>
        <p>
          <strong>描述：</strong>{{ currentScenicFeature.attributes.Description || '暂无描述' }}
        </p>
        <p><strong>门票：</strong>{{ currentScenicFeature.attributes.Price || '免费' }}</p>
        <p>
          <strong>所属景区：</strong>{{ currentScenicFeature.attributes.OwnerScenic || '未指定' }}
        </p>

        <!-- 维护信息 -->
        <div v-if="currentScenicFeature.attributes.MaintanceDataJson" class="maintenance-info">
          <el-divider content-position="left">维护信息</el-divider>
          <pre class="maintenance-data">{{
            formatMaintenanceData(currentScenicFeature.attributes.MaintanceDataJson)
          }}</pre>
        </div>

        <div class="details-actions">
          <el-button type="primary" @click="addScenicToFavorites(currentScenicFeature)">
            <el-icon><Star /></el-icon> 收藏
          </el-button>
        </div>
      </div>
      <div v-else class="no-feature-selected">
        <p>请选择一个景点查看详情</p>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, toRaw } from 'vue'
import { Search, Back, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'

import { gaodeLayer } from '@/utils/GaoDeBaseLayer' // Assuming this path is correct

// 用户存储和路由
// const userStore = useUserStore()
const router = useRouter()

// 地图和图层
let view
let featureLayer
let scenicFeatureLayer

// 数据类型切换
const dataType = ref('protectArea') // 'protectArea' 或 'scenicPoint'

// 保护区相关状态变量
const loading = ref(true)
const searchQuery = ref('')
const tableData = ref([])
const tableRef = ref(null) // Ref for el-table
const selectedFeatureId = ref(null)
const selectedFeatureName = ref('')
const selectedFeatureType = ref('')
const showDetailsDrawer = ref(false)
const currentFeature = ref(null) // Stores extracted attributes of the selected feature

// 景点相关状态变量
const scenicLoading = ref(true)
const scenicSearchQuery = ref('')
const scenicTableData = ref([])
const scenicTableRef = ref(null)
const selectedScenicFeatureId = ref(null)
const selectedScenicFeatureName = ref('')
const selectedScenicFeatureType = ref('')
const showScenicDetailsDrawer = ref(false)
const currentScenicFeature = ref(null)

const activeArea = ref('erdihu')

const areaCenters = {
  erdihu: [120.179558, 35.765965], // 胶南灵山岛坐标
  yunmen: [120.503415, 35.967122], // 大公岛坐标
  bailang: [120.022251, 37.00615], // 大泽山坐标
  xiashan: [120.605305, 36.198964], // 崂山坐标
  binhai: [119.93718, 36.121442], // 胶州艾山坐标
  mihe: [120.651138, 36.340289], // 马山坐标
}

const filteredTableData = computed(() => {
  if (!searchQuery.value) return tableData.value
  return tableData.value.filter(
    (item) =>
      item.attributes.Name &&
      item.attributes.Name.toLowerCase().includes(searchQuery.value.toLowerCase()),
  )
})

const filteredScenicTableData = computed(() => {
  if (!scenicSearchQuery.value) return scenicTableData.value
  return scenicTableData.value.filter(
    (item) =>
      item.attributes.ScenicName &&
      item.attributes.ScenicName.toLowerCase().includes(scenicSearchQuery.value.toLowerCase()),
  )
})

const extractFeatureData = (feature) => {
  if (!feature) return null

  // Use toRaw to avoid proxy access issues and extract plain objects
  const rawFeature = toRaw(feature)
  const attributes = rawFeature.attributes || feature.attributes
  const geometry = rawFeature.geometry || feature.geometry

  if (!attributes) return null

  // Extract geometry as plain object to avoid proxy issues
  let geometryInfo = null
  if (geometry) {
    geometryInfo = {
      x: geometry.x,
      y: geometry.y,
      type: geometry.type,
      // Extract other geometry properties as needed
      spatialReference: geometry.spatialReference
        ? {
            wkid: geometry.spatialReference.wkid,
            latestWkid: geometry.spatialReference.latestWkid,
          }
        : null,
    }
  }

  return {
    attributes: { ...attributes },
    geometryInfo: geometryInfo,
  }
}

const getTypeTagType = (type) => {
  switch (type) {
    case '自然风光':
      return 'success'
    case '历史文化':
      return 'danger'
    case '休闲娱乐':
      return 'primary'
    default:
      return 'info'
  }
}

const getScenicTypeTagType = (type) => {
  switch (type) {
    case '自然景观':
      return 'success'
    case '人文景观':
      return 'primary'
    case '历史遗迹':
      return 'warning'
    case '休闲娱乐':
      return 'info'
    case '观景台':
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case '正常开放':
      return 'success'
    case '维护中':
      return 'warning'
    case '暂停开放':
      return 'danger'
    case '季节性关闭':
      return 'info'
    default:
      return 'info'
  }
}

const formatMaintenanceData = (data) => {
  if (!data) return '无维护信息'
  try {
    const parsed = JSON.parse(data)
    return JSON.stringify(parsed, null, 2)
  } catch (e) {
    return data
  }
}

// Central function to handle feature selection
const selectFeature = (featureToSelect) => {
  if (!featureToSelect) {
    // Clear selection
    selectedFeatureId.value = null
    selectedFeatureName.value = ''
    selectedFeatureType.value = ''
    currentFeature.value = null

    const highlights = view?.graphics.filter((g) => g.attributes?.type === 'highlight')
    highlights?.forEach((g) => view.graphics.remove(g))

    if (tableRef.value) {
      tableRef.value.setCurrentRow(null)
    }

    return
  }

  // Use toRaw to avoid proxy access issues
  const rawFeature = toRaw(featureToSelect)
  const attributes = rawFeature.attributes || featureToSelect.attributes

  selectedFeatureId.value = attributes.FID
  selectedFeatureName.value = attributes.Name || `保护区 #${selectedFeatureId.value}`
  selectedFeatureType.value = attributes.AreaType || ''
  currentFeature.value = extractFeatureData(rawFeature)

  highlightFeatureOnMap(rawFeature) // Visual map highlight + re-draw connections

  if (tableRef.value) {
    const tableRowItem = tableData.value.find(
      (item) => item.attributes.FID === attributes.FID,
    )
    if (tableRowItem) {
      tableRef.value.setCurrentRow(tableRowItem)
    }
  }
}

// Central function to handle scenic point selection
const selectScenicFeature = (featureToSelect) => {
  if (!featureToSelect) {
    // Clear selection
    selectedScenicFeatureId.value = null
    selectedScenicFeatureName.value = ''
    selectedScenicFeatureType.value = ''
    currentScenicFeature.value = null

    const highlights = view?.graphics.filter((g) => g.attributes?.type === 'scenic-highlight')
    highlights?.forEach((g) => view.graphics.remove(g))

    if (scenicTableRef.value) {
      scenicTableRef.value.setCurrentRow(null)
    }

    return
  }

  // Use toRaw to avoid proxy access issues
  const rawFeature = toRaw(featureToSelect)
  const attributes = rawFeature.attributes || featureToSelect.attributes

  selectedScenicFeatureId.value = attributes.FID
  selectedScenicFeatureName.value = attributes.ScenicName || `景点 #${attributes.FID}`
  selectedScenicFeatureType.value = attributes.ScenicType || ''
  currentScenicFeature.value = extractFeatureData(rawFeature)

  highlightScenicFeatureOnMap(rawFeature)

  if (scenicTableRef.value) {
    const tableRowItem = scenicTableData.value.find(
      (item) => item.attributes.FID === attributes.FID,
    )
    if (tableRowItem) {
      scenicTableRef.value.setCurrentRow(tableRowItem)
    }
  }
}

// Handles only the visual highlighting on the map and view navigation
const highlightFeatureOnMap = (feature) => {
  if (!view) return

  // Clear previous highlights (but not connections)
  const highlights = view.graphics.filter((g) => g.attributes?.type === 'highlight')
  highlights.forEach((g) => view.graphics.remove(g))

  if (!feature || !feature.geometry) {
    return
  }

  // Create geometry object from plain data to avoid proxy issues
  let geometry
  if (feature.geometry.type === 'point') {
    geometry = {
      type: 'point',
      x: feature.geometry.x,
      y: feature.geometry.y,
      spatialReference: feature.geometry.spatialReference || { wkid: 4326 },
    }
  } else {
    // For other geometry types, use the geometry as is but ensure it's not proxied
    geometry = toRaw(feature.geometry)
  }

  // Enhanced highlight symbol
  const highlightSymbol = new SimpleMarkerSymbol({
    color: [255, 255, 0, 0.6], // Yellow, semi-transparent
    size: 22, // Larger
    outline: {
      color: [255, 160, 0], // Orange outline
      width: 2.5,
    },
  })

  const highlightGraphic = new Graphic({
    geometry: geometry,
    symbol: highlightSymbol,
    attributes: { type: 'highlight' }, // Tag for easy removal
  })
  view.graphics.add(highlightGraphic)

  view
    .goTo({
      target: geometry,
      // zoom: view.zoom > 16 ? view.zoom : 16, // Optional: zoom logic
    })
    .catch((e) => console.warn('Error going to feature:', e))
}

// Handles scenic point highlighting on the map
const highlightScenicFeatureOnMap = (feature) => {
  if (!view) return

  // Clear existing scenic highlights
  const highlights = view.graphics.filter((g) => g.attributes?.type === 'scenic-highlight')
  highlights.forEach((g) => view.graphics.remove(g))

  if (!feature || !feature.geometry) {
    return
  }

  // Create geometry object from plain data to avoid proxy issues
  let geometry
  if (feature.geometry.type === 'point') {
    geometry = {
      type: 'point',
      x: feature.geometry.x,
      y: feature.geometry.y,
      spatialReference: feature.geometry.spatialReference || { wkid: 4326 },
    }
  } else {
    // For other geometry types, use the geometry as is but ensure it's not proxied
    geometry = toRaw(feature.geometry)
  }

  // Create highlight graphic for scenic point
  const highlightSymbol = new SimpleMarkerSymbol({
    color: [255, 193, 7, 0.8],
    size: 22,
    outline: {
      color: [255, 87, 34],
      width: 3,
    },
  })

  const highlightGraphic = new Graphic({
    geometry: geometry,
    symbol: highlightSymbol,
    attributes: { type: 'scenic-highlight' },
  })

  view.graphics.add(highlightGraphic)

  // Navigate to feature
  view
    .goTo({
      target: geometry,
    })
    .catch((e) => console.warn('Error going to scenic feature:', e))
}

const queryFeatures = async () => {
  if (!featureLayer) return
  loading.value = true
  try {
    const query = featureLayer.createQuery()
    const currentAreaName = getCurrentAreaName()
    let whereClause = `OwnerArea='${currentAreaName}'` // Simplified: only show for current area
    // OR OwnerScenic IS NULL - if you have general points

    if (searchQuery.value) {
      whereClause += ` AND Name LIKE '%${searchQuery.value}%'`
    }
    query.where = whereClause
    query.outFields = ['*']
    const result = await featureLayer.queryFeatures(query)
    // Extract features as plain objects to avoid proxy issues
    const extractedFeatures = result.features.map((feature) => {
      const rawFeature = toRaw(feature)
      return {
        attributes: { ...rawFeature.attributes },
        geometry: rawFeature.geometry
          ? {
              x: rawFeature.geometry.x,
              y: rawFeature.geometry.y,
              type: rawFeature.geometry.type,
              spatialReference: rawFeature.geometry.spatialReference
                ? {
                    wkid: rawFeature.geometry.spatialReference.wkid,
                    latestWkid: rawFeature.geometry.spatialReference.latestWkid,
                  }
                : null,
            }
          : null,
      }
    })

    window._tempFeatures = extractedFeatures
    tableData.value = extractedFeatures.map((feature, index) => ({
      _index: index,
      attributes: { ...feature.attributes },
      geometry: feature.geometry,
    }))
  } catch (error) {
    console.error('查询保护区数据失败', error)
    tableData.value = []
    window._tempFeatures = []
  } finally {
    loading.value = false
  }
}

// Query scenic points from the FeatureLayer
const queryScenicFeatures = async () => {
  if (!scenicFeatureLayer) return

  try {
    scenicLoading.value = true
    const query = scenicFeatureLayer.createQuery()
    const currentAreaName = getCurrentAreaName()
    query.where = `OwnerScenic='${currentAreaName}'` // Get all features
    query.outFields = ['*']
    query.returnGeometry = true

    const result = await scenicFeatureLayer.queryFeatures(query)
    // Extract scenic features as plain objects to avoid proxy issues
    const extractedScenicFeatures = result.features.map((feature) => {
      const rawFeature = toRaw(feature)
      return {
        attributes: { ...rawFeature.attributes },
        geometry: rawFeature.geometry
          ? {
              x: rawFeature.geometry.x,
              y: rawFeature.geometry.y,
              type: rawFeature.geometry.type,
              spatialReference: rawFeature.geometry.spatialReference
                ? {
                    wkid: rawFeature.geometry.spatialReference.wkid,
                    latestWkid: rawFeature.geometry.spatialReference.latestWkid,
                  }
                : null,
            }
          : null,
      }
    })

    scenicTableData.value = extractedScenicFeatures
  } catch (error) {
    console.error('Error querying scenic features:', error)
    ElMessage.error('查询景点数据失败')
  } finally {
    scenicLoading.value = false
  }
}

watch(searchQuery, () => {
  if (dataType.value === 'protectArea') {
    queryFeatures()
  }
})

watch(scenicSearchQuery, () => {
  if (dataType.value === 'scenicPoint') {
    queryScenicFeatures()
  }
})

watch(dataType, () => {
  handleDataTypeChange()
})

const initMap = async () => {
  const map = new Map({
    basemap: 'streets-vector',
  })
  view = new MapView({
    container: 'guideMapView',
    map: map,
    center: areaCenters[activeArea.value],
    zoom: 15,
    popup: { dockEnabled: true, dockOptions: { buttonEnabled: false, breakpoint: false } },
  })

  const featureLayerHe = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/hexinFeaturelayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple', // autocasts as new SimpleRenderer()
      symbol: {
        type: 'simple-fill', // autocasts as new SimpleMarkerSymbol()
        color: [225, 76, 66, 0.5], // 红色
        outline: {
          // autocasts as new SimpleLineSymbol()
          width: 0.5,
          color: 'white',
        },
      },
    },
  })
  const featureLayerHu = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/huanchong/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple', // autocasts as new SimpleRenderer()
      symbol: {
        type: 'simple-fill', // autocasts as new SimpleMarkerSymbol()
        color: [0, 112, 255, 0.5], // 蓝色
        outline: {
          // autocasts as new SimpleLineSymbol()
          width: 0.5,
          color: 'white',
        },
      },
    },
  })
  const featureLayerS = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/shiyan/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-fill',
        color: [56, 168, 0, 0.5], // 绿色
        outline: {
          // autocasts as new SimpleLineSymbol()
          width: 0.5,
          color: 'white',
        },
      },
    },
  })
  map.add(featureLayerHe)
  map.add(featureLayerHu)
  map.add(featureLayerS)

  // Create the FeatureLayer for scenic points
  scenicFeatureLayer = new FeatureLayer({
    url: 'https://services8.arcgis.com/hvBaJk0FLVU4yP47/arcgis/rest/services/ScenicPointLayer/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: 'simple',
      symbol: {
        type: 'simple-marker',
        color: [0, 123, 255, 0.8],
        size: '8px',
        outline: {
          color: [255, 255, 255],
          width: 1,
        },
      },
    },
  })
  map.add(scenicFeatureLayer)

  view.on('click', async (event) => {
    const hitResults = (await view?.hitTest(event))?.results
    const protectAreaGraphic = hitResults?.find(
      (result) => result.layer?.id === featureLayer?.id,
    )?.graphic
    const scenicGraphic = hitResults?.find(
      (result) => result.layer?.id === scenicFeatureLayer?.id,
    )?.graphic

    if (dataType.value === 'protectArea' && protectAreaGraphic) {
      // Extract graphic as plain object to avoid proxy issues
      const extractedGraphic = {
        attributes: { ...toRaw(protectAreaGraphic).attributes },
        geometry: {
          x: protectAreaGraphic.geometry.x,
          y: protectAreaGraphic.geometry.y,
          type: protectAreaGraphic.geometry.type,
          spatialReference: protectAreaGraphic.geometry.spatialReference
            ? {
                wkid: protectAreaGraphic.geometry.spatialReference.wkid,
                latestWkid: protectAreaGraphic.geometry.spatialReference.latestWkid,
              }
            : null,
        },
      }
      selectFeature(extractedGraphic)
      showDetailsDrawer.value = true // Auto-open drawer
    } else if (dataType.value === 'scenicPoint' && scenicGraphic) {
      // Extract graphic as plain object to avoid proxy issues
      const extractedScenicGraphic = {
        attributes: { ...toRaw(scenicGraphic).attributes },
        geometry: {
          x: scenicGraphic.geometry.x,
          y: scenicGraphic.geometry.y,
          type: scenicGraphic.geometry.type,
          spatialReference: scenicGraphic.geometry.spatialReference
            ? {
                wkid: scenicGraphic.geometry.spatialReference.wkid,
                latestWkid: scenicGraphic.geometry.spatialReference.latestWkid,
              }
            : null,
        },
      }
      selectScenicFeature(extractedScenicGraphic)
      showScenicDetailsDrawer.value = true // Auto-open drawer
    } else {
      if (dataType.value === 'protectArea') {
        selectFeature(null) // Clear selection if clicking map background
      } else {
        selectScenicFeature(null) // Clear selection if clicking map background
      }
    }
  })

  await loadFeatures()
}

const loadFeatures = async () => {
  await queryFeatures()
  // Connection drawing is now handled in queryFeatures' finally block
}

const getCurrentAreaName = () => {
  const names = {
    erdihu: '胶南灵山岛保护区',
    yunmen: '大公岛保护区',
    bailang: '大泽山保护区',
    xiashan: '崂山保护区',
    binhai: '胶州艾山保护区',
    mihe: '马山保护区',
  }
  return names[activeArea.value] || ''
}

const handleAreaChange = async () => {
  selectFeature(null) // Clear selection from previous area

  if (view && areaCenters[activeArea.value]) {
    await view
      .goTo({
        // Await this initial goTo
        center: areaCenters[activeArea.value],
        zoom: 13, // Start a bit zoomed out
      })
      .catch((e) => console.warn('Error in initial goTo for area change:', e))
  }

  await loadFeatures() // This populates window._tempFeatures

  if (view && window._tempFeatures && window._tempFeatures.length > 0) {
    const currentAreaNameFilter = getCurrentAreaName() // Ensure we only zoom to features of the *current* area
    const featuresInCurrentArea = window._tempFeatures.filter(
      (f) => f.attributes.OwnerArea === currentAreaNameFilter,
    )
    if (featuresInCurrentArea.length > 0) {
      // Create plain geometry objects for goTo to avoid proxy issues
      const plainGeometries = featuresInCurrentArea
        .map((feature) => {
          if (feature.geometry) {
            return {
              type: feature.geometry.type,
              x: feature.geometry.x,
              y: feature.geometry.y,
              spatialReference: feature.geometry.spatialReference || { wkid: 4326 },
            }
          }
          return null
        })
        .filter(Boolean)

      if (plainGeometries.length > 0) {
        view.goTo(plainGeometries).catch((error) => {
          console.warn('Could not zoom to features extent:', error)
          if (areaCenters[activeArea.value]) {
            // Fallback
            view.goTo({ center: areaCenters[activeArea.value], zoom: 15 })
          }
        })
      }
    } else if (areaCenters[activeArea.value]) {
      view.goTo({ center: areaCenters[activeArea.value], zoom: 15 })
    }
  } else if (view && areaCenters[activeArea.value]) {
    // Fallback if no features loaded
    view.goTo({ center: areaCenters[activeArea.value], zoom: 15 })
  }
}

// For the "Details" button in the table
const viewFeatureDetailsFromButton = (row) => {
  if (row._index !== undefined) {
    const originalFeature = window._tempFeatures?.[row._index]
    if (originalFeature) {
      selectFeature(originalFeature)
      showDetailsDrawer.value = true
    }
  }
}

const handleRowClick = (row) => {
  const originalFeature = window._tempFeatures?.[row._index]
  if (originalFeature) {
    selectFeature(originalFeature)
    // Clicking a row will select and highlight, but not open drawer by default.
    // Drawer opens via map click or "Details" button.
  }
}

const addToFavorites = (feature) => {
  if (!feature) return
  ElMessage.success(`已收藏保护区: ${feature.attributes.Name}`)
}

const goBack = () => {
  router.push('/')
}

// 景点相关事件处理
const viewScenicDetailsFromButton = (row) => {
  if (row.attributes) {
    selectScenicFeature(row)
    showScenicDetailsDrawer.value = true
  }
}

const handleScenicRowClick = (row) => {
  selectScenicFeature(row)
}

const addScenicToFavorites = (feature) => {
  if (!feature) return
  ElMessage.success(`已收藏景点: ${feature.attributes.ScenicName}`)
}

// 数据类型切换处理
const handleDataTypeChange = () => {
  // 清除当前选择
  if (dataType.value === 'protectArea') {
    selectScenicFeature(null)
    showScenicDetailsDrawer.value = false
    // 显示保护区图层，隐藏景点图层
    if (featureLayer) featureLayer.visible = true
    if (scenicFeatureLayer) scenicFeatureLayer.visible = false
    queryFeatures()
  } else {
    selectFeature(null)
    showDetailsDrawer.value = false
    // 显示景点图层，隐藏保护区图层
    if (featureLayer) featureLayer.visible = false
    if (scenicFeatureLayer) scenicFeatureLayer.visible = true
    queryScenicFeatures()
  }
}

watch(activeArea, () => {
  handleAreaChange()
})

onMounted(() => {
  initMap()
})
</script>

<style scoped lang="scss">
.scenic-guide-container {
  padding: 20px;
}

.scenic-guide-header {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-left: 4px solid #67c23a;
}

.header-actions {
  margin-bottom: 15px;
}

.scenic-guide-header h1 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 8px;
}

.scenic-guide-header p {
  color: #606266;
  font-size: 14px;
}

.map-container {
  height: 500px; /* Or adjust as needed, e.g., calc(100vh - header_height - padding etc.) */
  width: 100%;
  position: relative;
}

.map-card,
.feature-list-card,
.area-select-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  overflow: hidden; /* Important for card content */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  width: 200px;
}

.connection-toggle {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px 10px; /* Added bottom padding */

  .loading-icon {
    margin-left: 10px;
    color: #409eff;
  }
}

.route-info {
  margin-top: 15px;
  padding: 0 20px 10px;
}

/* Styling for highlighted row in el-table */
:deep(.el-table__row.current-row > td.el-table__cell) {
  background-color: #e6f7ff !important; /* A light blue, or your preferred highlight color */
}
:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: #e6f7ff !important;
}

.feature-details {
  padding: 20px;
}

.details-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-feature-selected {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px; /* Or adjust as needed */
  color: #909399;
}

@media (max-width: 768px) {
  .scenic-guide-container {
    padding: 10px;
  }
  .map-container {
    height: 350px;
  }
  .search-input {
    width: 100%; /* Full width on smaller screens */
    margin-top: 10px;
  }
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  .el-col {
    // Stack columns on mobile
    width: 100% !important;
    max-width: 100% !important;
    flex: 0 0 100% !important;
  }
}
</style>
